package cn.samler.account_manager.handler;

import cn.samler.account_manager.model.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@Slf4j
public class RequestExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Response handler(Exception e) {
        if (e instanceof MethodArgumentNotValidException) {
            String errMsg = null;
            for (ObjectError err : ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors()) {
                errMsg = err.getDefaultMessage();

                break;
            }

            return Response.builder().ret(Response.Ret.FAILURE).msg("请求发生错误").data(errMsg).build();
        }

        return Response.builder().ret(Response.Ret.FAILURE).msg(e.getMessage()).build();
    }

}
